import { createElement, InputHTMLAttributes, type FC } from 'react';
import classNames from 'classnames';
import Icon, { IconProps } from '../icon';
import { inputDefaultProps } from './defaultProps';
import { InputOptions, InputIconOptions, InputLabeledOptions } from './type';

export interface InputProps extends InputOptions, InputHTMLAttributes<HTMLInputElement> {}

const Input: FC<InputProps> = (props) => {
  const { className, type, focus, disabled, state, loading, speed, icon, labeled, forwardedRef, ...inputProps } = props;

  let content: Array<JSX.Element> = [];

  if (labeled && (labeled as InputLabeledOptions).position !== 'right') {
    content.push(
      createElement(
        'div',
        { key: 'labeled', className: classNames('ui', 'label') },
        typeof labeled === 'string' ? labeled : labeled.content,
      ),
    );
  }

  content.push(createElement('input', { key: 'input', type, ...inputProps }));

  if (loading || icon) {
    content.push(
      createElement(Icon, {
        key: 'icon',
        name: (icon as InputIconOptions).name || 'search',
        color: (icon as InputIconOptions).color,
        circular: (icon as InputIconOptions).circular,
        link: (icon as InputIconOptions).link,
        inverted: (icon as InputIconOptions).inverted,
      } as IconProps),
    );
  }
  //  TODO 带完成 dropdown
  if (labeled && (labeled as InputLabeledOptions).position === 'right') {
    content.push(
      createElement(
        'div',
        { key: 'labeled', className: classNames('ui', { dropdown: (labeled as InputLabeledOptions).menu }, 'label') },
        (labeled as InputLabeledOptions).menu ? (
          <>
            <div className="text">{(labeled as InputLabeledOptions).content}</div>
            <Icon name="dropdown" />
            <div className="menu">
              <div className="item">.com</div>
              <div className="item">.cn</div>
              <div className="item">.net</div>
              <div className="item">.org</div>
            </div>
          </>
        ) : (
          (labeled as InputLabeledOptions).content
        ),
      ),
    );
  }

  return createElement(
    'div',
    {
      ref: forwardedRef,
      className: classNames(
        'ui',
        {
          file: type === 'file',
          focus,
          disabled,
          left: (icon as InputIconOptions).position === 'left',
          icon: loading || icon,
          right: (labeled as InputLabeledOptions).position === 'right',
          labeled,
        },
        'input',
        (icon as InputIconOptions).color,
        speed,
        loading,
        { loading },
        state,
        className,
      ),
    },
    content,
  );
};

Input.displayName = 'Input';
Input.defaultProps = inputDefaultProps;

export default Input;
